<?php

namespace services\hiss;

use common\models\base\Profession;
use common\models\clinic\UserTreatment;
use common\models\clinic\UserTreatmentDetail;
use Yii;
use common\models\base\BcBodyParts;
use common\models\base\BodyParts;
use common\models\base\PatientDiseases;
use common\models\common\Provinces;
use common\models\hiss\Model;
use common\models\marketing\Tags;
use common\models\member\Attr;
use common\models\member\Member;
use common\models\patient\Callback;
use common\models\patient\MedicalRecords;
use common\models\patient\User;
use common\models\rbac\Department;
use common\components\Service;
use yii\db\Expression;

//use \Swoole\Process;

/**
 * Class BodyPartsService
 * @package services\patient
 */
class DataMigrateService extends Service
{
    public static $projectId;


    /**
     * 同步用户
     *
     * @param int $projectId
     * @throws \Exception
     * @author wangxiang
     */
    public static function user(int $projectId)
    {
        self::$projectId = $projectId;
        Model::setTableName('jg_user');
        $data = Model::find()->where(['!=', 'role_id', 0])->andWhere(['state' => 1])->asArray()->all();
        $transaction = Yii::$app->db->beginTransaction();
        try {
            foreach ($data as $user) {
                // 判断用户是否存在
                $memberModel = Member::find()->where(['ding_unionid' => $user['ding_unionid']])->one();
                if (!$memberModel) {
                    $memberModel = new Member;
                    $memberModel->ding_unionid = $user['union_id'];
                    $memberModel->user_id = $user['user_id'];
                    $memberModel->username = $user['user_name'];
                    $memberModel->mobile = $user['tel'];
                    $memberModel->password_hash = Yii::$app->security->generatePasswordHash('123456');
                    $memberModel->auth_key = Yii::$app->security->generateRandomString();
                    $memberModel->realname = $user['user_name'];
                    $memberModel->job_title = '';
                    //$memberModel->password_reset_token = '';
                    $memberModel->gender = $user['sex'];
                    $memberModel->email = '';
                    $memberModel->visit_count = 0;
                    $memberModel->last_time = $user['last_login_time'] != '0000-00-00 00:00:00' ? strtotime($user['last_login_time']) : 0;
                    $memberModel->last_ip = $user['last_login_ip'];
                    //$memberModel->status = '';
                    //$memberModel->is_super = '';
                    //$memberModel->created_at = '';
                    //$memberModel->updated_at = '';
                    if (!$memberModel->save()) {
                        throw new \Exception(json_encode($memberModel->errors), 500);
                    }
                }

                $memberId = $memberModel->id;
                $memberAttrModel = Attr::find()->where(['member_id' => $memberId, 'project_id' => self::$projectId])->one();
                if (!$memberAttrModel) {
                    $memberAttrModel = new Attr;
                    $memberAttrModel->member_id = $memberId;
                    $memberAttrModel->project_id = self::$projectId;
                    if (!$memberAttrModel->save()) {
                        throw new \Exception(json_encode($memberAttrModel->errors), 500);
                    }
                }
            }
            $transaction->commit();
        } catch (\Exception $exception) {
            $transaction->rollBack();
            throw new \Exception($exception->getMessage(), 500);
        }

    }


    /**
     * 同步患者
     *
     * @param int $projectId
     * @throws \Exception
     * @author wangxiang
     */
    public static function patient(int $projectId)
    {
        $fileName = '/data/wwwlogs/hiss_patient_mobile_record.txt';
        // $fileName = 'test.txt';
        self::$projectId = $projectId;
        $baiyouData = User::find()->where(['project_id' => self::$projectId])->orderBy('id')->select('patient_card_id')->asArray()->column();
        file_put_contents($fileName, '*********************项目：' . $projectId . '  START ***********************' . PHP_EOL, FILE_APPEND);
        foreach ($baiyouData as $patientCardId) {
            $transaction = Yii::$app->db->beginTransaction();
            try {
                // 处理患者主表数据
                Model::setTableName('jg_patient_info');
                $hissPatient = Model::find()->where(['treat_number' => $patientCardId])->orderBy('show DESC')->asArray()->one();
                if (!$hissPatient) {
                    // 如果数据不存在， 则跳过
                    $transaction->rollBack();
                    continue;
                }
                $patientUserModel = User::find()->where(['project_id' => self::$projectId, 'patient_card_id' => $patientCardId])->one();
                !$patientUserModel->name && $patientUserModel->name = $hissPatient['name'];
                $patientUserModel->birthday == '0000-00-00' && $patientUserModel->birthday = ((date('Y') - $hissPatient['age']) . '-00-00');
                !$patientUserModel->age && $patientUserModel->age = $hissPatient['age'];
                !$patientUserModel->wx_name && $patientUserModel->wx_name = $hissPatient['weixin'];
                !$patientUserModel->source_channel_id && $patientUserModel->source_channel_id = ConfigService::SOURCE_CHANNEL[self::$projectId][$hissPatient['qudao_id']] ?? 0;
                $patientUserModel->gender = $hissPatient['sex'];

                if ($hissPatient && $hissPatient['tel'] && $hissPatient['tel'] != '--' && $hissPatient['tel'] != $patientUserModel->mobile) {
                    // 判断手机号是否为正常的
                    if (preg_match("/^1[3456789]{1}\d{9}$/", $hissPatient['tel'])) {
                        $patientUserModel->mobile = $hissPatient['tel'];
                    } else {
                        file_put_contents($fileName, $patientUserModel->name . '《==》' . $patientCardId . '《==》白友手机号：' . $patientUserModel->mobile . '《==》hiss手机号：' . $hissPatient['tel'] . PHP_EOL, FILE_APPEND);
                    }
                }

                /*if (!$patientUserModel->mobile && $hissPatient['tel'] && $hissPatient['tel'] != '--') {
                    $telData = explode('/', $hissPatient['tel']);
                    (isset($telData[0]) && $telData[0]) && $patientUserModel->mobile = $telData[0];
                    if (count($telData) > 1) {
                        unset($telData[0]);
                        $patientUserModel->remark = implode('/', $telData);
                    }
                }*/

                if (!$patientUserModel->city_id && $hissPatient['city']) {
                    $city = Provinces::find()->where(['level' => Provinces::LEVEL_CITY, 'title' => $hissPatient['city']])->one();
                    $city && $patientUserModel->city_id = $city->id;
                }

                (!$patientUserModel->city_name && $hissPatient['city']) && $patientUserModel->city_name = $hissPatient['city'];
                !$patientUserModel->address && $patientUserModel->address = $hissPatient['address'];

                $patientUserModel->patient_diseases_id = ConfigService::PATIENT_DISEASES[self::$projectId][$hissPatient['ill_type']] ?? 0;

                /*处理部位数据开始*/
                $hissPositionData = array_unique(array_filter(explode(',', $hissPatient['position'])));
                $bodyPartsIdData = BodyParts::find()->where(['pid' => 0, 'body_parts_name' => $hissPositionData])->select(['id', 'body_parts_name'])->asArray()->all();
                $bodyPartInsertData = [];
                $bodyPartNameData = [];
                foreach ($bodyPartsIdData as $bodyPartsList) {
                    $bodyPartNameData[$bodyPartsList['id']] = $bodyPartsList['body_parts_name'];
                    $flag = \common\models\patient\BodyParts::find()->where(['patient_user_id' => $patientUserModel->id, 'body_parts_id' => $bodyPartsList['id']])->exists();
                    if (!$flag) {
                        $bodyPartInsertData[$bodyPartsList['id']] = [
                            'patient_user_id' => $patientUserModel->id,
                            'body_parts_id' => $bodyPartsList['id'],
                            'created_at' => time(),
                            'updated_at' => time(),
                        ];
                    }
                }
                $bodyPartNameData && $patientUserModel->patient_body_parts_name = implode(',', $bodyPartNameData);
                $bodyPartInsertData && Yii::$app->db->createCommand()->batchInsert(\common\models\patient\BodyParts::tableName(), ['patient_user_id', 'body_parts_id', 'created_at', 'updated_at'], $bodyPartInsertData)->execute();
                /*处理部位数据结束*/

                /*标签处理开始*/
                $labelData = array_unique(array_filter(explode(',', $hissPatient['lable'])));
                $tagsData = [];
                $tagsInsertData = [];
                foreach ($labelData as $labelId) {
                    $newTagsId = ConfigService::PATIENT_LABEL[self::$projectId][$labelId] ?? 0;
                    if (!$newTagsId) {
                        continue;
                    }
                    $tagsData[$newTagsId] = $newTagsId;
                    $flag = \common\models\patient\Tags::find()->where(['tags_id' => $newTagsId, 'patient_user_id' => $patientUserModel->id])->exists();
                    // 如果患者不存在这个标签， 则增加
                    if (!$flag) {
                        $tagsInsertData[$newTagsId] = [
                            'patient_user_id' => $patientUserModel->id,
                            'tags_id' => $newTagsId,
                            'created_at' => time(),
                            'updated_at' => time(),
                        ];
                    }
                }
                if ($tagsData) {
                    $tagsNameData = Tags::find()->where(['id' => $tagsData])->select('tags_name')->asArray()->column();
                    $tagsNameData && $patientUserModel->patient_tags_name = implode(',', $tagsNameData);
                    $tagsInsertData && Yii::$app->db->createCommand()->batchInsert(\common\models\patient\Tags::tableName(), ['patient_user_id', 'tags_id', 'created_at', 'updated_at'], $tagsInsertData)->execute();
                }
                /*标签处理结束*/

                /*处理医助归属人和客服归属人开始*/
                $assistantData = self::getMemberByHissUserId($hissPatient['handle_id']);
                $customerData = self::getMemberByHissUserId($hissPatient['customer_id']);
                $belongAssistantId = $assistantData['id'] ?? 0;
                if ($hissPatient['handle_id'] && $belongAssistantId) {
                    // 处理医助， 如果是北大项目且诊室不为六诊或不是北大的项目， 才更新
                    $consultRoomId = ConfigService::CLINIC[self::$projectId][$hissPatient['consult_room_id']] ?? 0;
                    if (self::$projectId != ConfigService::PROJECT['bd'] || $consultRoomId != 10) {
                        $patientUserModel->belong_assistant_id = $belongAssistantId;
                    }
                }

                if ($hissPatient['customer_id']) {
                    $patientUserModel->belong_member_id = $customerData['id'] ?? 0;
                    $patientUserModel->belong_member_name = $customerData['realname'] ?? '';
                }

                /*处理医助归属人和客服归属人结束*/

                /*处理治疗类型开始*/
                $effectTypeId_1 = ConfigService::EFFECT_TYPE[self::$projectId]['hiss_fz'][$hissPatient['state']] ?? 0;
                $effectTypeId_2 = ConfigService::EFFECT_TYPE[self::$projectId]['hiss_zl'][$hissPatient['treat_type']] ?? 0;

                $riskTypeId_1 = ConfigService::RISK_TYPE[self::$projectId]['hiss_fz'][$hissPatient['state']] ?? 0;
                $riskTypeId_2 = ConfigService::RISK_TYPE[self::$projectId]['hiss_zl'][$hissPatient['treat_type']] ?? 0;

                $clinicAssessId_1 = ConfigService::CLINIC_ASSESS[self::$projectId]['hiss_fz'][$hissPatient['state']] ?? 0;
                $clinicAssessId_2 = ConfigService::CLINIC_ASSESS[self::$projectId]['hiss_zl'][$hissPatient['treat_type']] ?? 0;


                $outpatientTypeId_1 = ConfigService::OUTPATIENT_TYPE[self::$projectId]['hiss_fz'][$hissPatient['state']] ?? 0;
                $outpatientTypeId_2 = ConfigService::OUTPATIENT_TYPE[self::$projectId]['hiss_zl'][$hissPatient['treat_type']] ?? 0;

                $patientUserModel->effect_type_id = $effectTypeId_1 ?: $effectTypeId_2;
                $patientUserModel->risk_type_id = $riskTypeId_1 ?: $riskTypeId_2;
                $patientUserModel->clinic_assess_id = $clinicAssessId_1 ?: $clinicAssessId_2;
                if (!in_array(self::$projectId, [ConfigService::PROJECT['bd'], ConfigService::PROJECT['gz'], ConfigService::PROJECT['cs']])) {
                    if ($outpatientTypeId_1 || $outpatientTypeId_2) {
                        $patientUserModel->outpatient_type_id = $outpatientTypeId_1 ?: $outpatientTypeId_2;
                    }
                }

                $isAntiRelapse_1 = in_array($hissPatient['state'], ConfigService::IS_ANTI_RELAPSE[self::$projectId]['hiss_fz']);
                $isAntiRelapse_2 = in_array($hissPatient['treat_type'], ConfigService::IS_ANTI_RELAPSE[self::$projectId]['hiss_zl']);
                $patientUserModel->is_anti_relapse = ($isAntiRelapse_1 || $isAntiRelapse_2) ? 1 : 0;
                /*处理治疗类型结束*/

                // 取患者最后一次的治疗时间
                Model::setTableName('jg_treat');
                $lastClinicTime = (int)Model::find()->where(['patient_id' => $hissPatient['patient_id']])->orderBy('add_time DESC')->select('add_time')->scalar();
                $patientUserModel->last_clinic_time = $lastClinicTime;

                if (in_array(self::$projectId, [ConfigService::PROJECT['nc'], ConfigService::PROJECT['nt'], ConfigService::PROJECT['nb'], ConfigService::PROJECT['bd']])) {
                    $patientUserModel->clinic_id = ConfigService::CLINIC[self::$projectId][$hissPatient['consult_room_id']] ?? 0;
                } else {
                    !$patientUserModel->clinic_id && $patientUserModel->clinic_id = ConfigService::CLINIC[self::$projectId][$hissPatient['consult_room_id']] ?? 0;
                }
                $patientUserModel->profession = $hissPatient['job'] ?? '';

                // 判断hiss那边的下次回访时间是否有, 如果没有则取当前时间后两天
                $nextCallbackTime = $hissPatient['next_follow_time'];
                if (!$nextCallbackTime) {
                    $nextCallbackTime = (int)strtotime("+2 days");
                }
                $patientUserModel->yz_next_callback_time = $nextCallbackTime;
                $patientUserModel->yz_last_callback_time = $hissPatient['last_follow_time'];
                if (in_array($hissPatient['state'], ConfigService::DIAGNOSIS[self::$projectId])) {
                    // 如果该患者在hiss中是断诊状态时
                    $patientUserModel->kf_next_callback_time = $nextCallbackTime;
                    $patientUserModel->kf_last_callback_time = $hissPatient['last_follow_time'];
                }

                // 针对修复数据， 取回访记录中的数据中最后一次回访时间， 如果是客服回访的则更新客服， 如果是医助回访的则更新自助
                if (in_array(self::$projectId, [ConfigService::PROJECT['hy']])) {
                    Model::setTableName('jg_patient_follow');
                    $hissFollowOne = Model::find()->where(['patient_id' => $hissPatient['patient_id']])->orderBy('follow_time DESC')->asArray()->one();
                    if ($hissFollowOne['type'] == 1) {
                        // 医助
                        !$patientUserModel->yz_last_callback_time && $patientUserModel->yz_last_callback_time = $hissFollowOne['follow_time'];
                    } else if ($hissFollowOne['type'] == 2) {
                        // 客服
                        !$patientUserModel->kf_last_callback_time && $patientUserModel->kf_last_callback_time = $hissFollowOne['follow_time'];
                    }
                }

                //$patientUserModel->last_callback_time = $hissPatient['last_follow_time'];   // 上次回访日期     作废
                //$patientUserModel->next_callback_time = $hissPatient['next_follow_time'];   // 下次回访日期     作废

                $patientUserModel->last_revisiting_time = $hissPatient['last_in_time']; // 上次到诊日期
                $patientUserModel->next_revisiting_time = $hissPatient['order_time']; // 下次复诊日期

                // 处理患者上次回访的医助和客服
                Model::setTableName('jg_patient_follow');
                $yzFollowUser = (string)Model::find()
                    ->alias('f')
                    ->leftJoin('jg_user', 'jg_user.id = f.follow_user')
                    ->where(['f.patient_id' => $hissPatient['patient_id'], 'f.type' => 1])
                    ->orderBy('f.follow_time DESC')
                    ->select('jg_user.user_name')
                    ->scalar();

                $kfFollowUser = (string)Model::find()
                    ->alias('f')
                    ->leftJoin('jg_user', 'jg_user.id = f.follow_user')
                    ->where(['f.patient_id' => $hissPatient['patient_id'], 'f.type' => 2])
                    ->orderBy('f.follow_time DESC')
                    ->select('jg_user.user_name')
                    ->scalar();

                $patientUserModel->kf_last_callback_user = $kfFollowUser;
                $patientUserModel->yz_last_callback_user = $yzFollowUser;

                // 获取回访次数
                Model::setTableName('jg_patient_follow');
                $callbackCount = Model::find()->where(['patient_id' => $hissPatient['patient_id']])->count();
                $patientUserModel->yz_callback_count = $callbackCount;

                // 获取来院次数
                Model::setTableName('jg_patient_record');
                $revisitingCount = Model::find()
                    ->where(['patient_id' => $hissPatient['patient_id']])
                    ->groupBy(['UNIX_TIMESTAMP(FROM_UNIXTIME(`in_time`, "%Y-%m-%d"))'])
                    ->count();
                $patientUserModel->revisiting_count = $revisitingCount;

                /*// 获取患者的导诊数据
                Model::setTableName('jg_patient_record');
                $firstInTime = (int) Model::find()->where(['patient_id' => $hissPatient['patient_id']])->orderBy('in_time ASC')->select('in_time')->scalar();
                if ($firstInTime) {
                    // 获取当月时间结束点
                    $d = date('t', $firstInTime);
                    $endTime = mktime(23,59,59, date('m', $firstInTime), $d, date('Y', $firstInTime));
                    $revisitingCount = Model::find()->where(['patient_id' => $hissPatient['patient_id']])->andWhere(['>', 'in_time', $endTime])->count();
                    $patientUserModel->revisiting_count = $revisitingCount;
                }*/

                if ($patientUserModel->remark) {
                    $patientUserModel->remark .= ',' . $hissPatient['remark'];
                } else {
                    $patientUserModel->remark = $hissPatient['remark'];
                }

                if (!$patientUserModel->save()) {
                    throw new \Exception(json_encode($patientUserModel->errors), 500);
                }


                // 处理患者回访数据
                Model::setTableName('jg_patient_follow');
                $hissFollowData = Model::find()->where(['patient_id' => $hissPatient['patient_id']])->asArray()->all();
                $followInsertData = [];
                foreach ($hissFollowData as $list) {
                    $flag = Callback::find()->where(['project_id' => self::$projectId, 'patient_user_id' => $patientUserModel->id, 'current_callback_time' => $list['follow_time']])->exists();
                    if ($flag) {
                        continue;
                    }
                    $memberInfo = self::getMemberByHissUserId($list['follow_user']);
                    $followInsertData[] = [
                        'project_id' => self::$projectId,
                        'patient_user_id' => $patientUserModel->id,
                        'callback_state_id' => ConfigService::FOLLOW_RESULT[self::$projectId]['id'][$list['follow_result']] ?? 0,
                        'callback_state' => ConfigService::FOLLOW_RESULT[self::$projectId]['title'][$list['follow_result']] ?? '',
                        'callback_way_id' => ConfigService::FOLLOW_TYPE[self::$projectId][$list['follow_type']] ?? 4,
                        'content' => $list['follow'],
                        'current_callback_time' => (int)$list['follow_time'],
                        'outpatient_type_id' => $patientUserModel->outpatient_type_id,
                        'next_callback_time' => $patientUserModel->next_callback_time,
                        'next_fuzhen_time' => $hissPatient['order_time'],
                        'member_id' => $memberInfo['id'] ?? 0,
                        'member_name' => $memberInfo['realname'] ?? '',
                        'member_departmement' => $memberInfo['department_name'] ?? '',
                        'created_at' => (int)$list['follow_time'],
                        'updated_at' => (int)$list['follow_time']
                    ];
                }

                $followInsertData && Yii::$app->db->createCommand()->batchInsert(Callback::tableName(),
                    ['project_id', 'patient_user_id', 'callback_state_id', 'callback_state', 'callback_way_id',
                        'content', 'current_callback_time', 'outpatient_type_id', 'next_callback_time',
                        'next_fuzhen_time', 'member_id', 'member_name', 'member_departmement', 'created_at', 'updated_at'
                    ], $followInsertData)->execute();


                // 处理患者病历数据
                Model::setTableName('jg_patient_detail');
                $hissPatientDetailData = Model::find()->where(['patient_id' => $hissPatient['patient_id']])->asArray()->one();
                if ($hissPatientDetailData) {
                    $model = MedicalRecords::find()->where(['patient_user_id' => $patientUserModel->id, 'project_id' => self::$projectId])->one();
                    if (!$model) {
                        $model = new MedicalRecords;
                    }
                    $model->project_id = self::$projectId;
                    $model->patient_user_id = $patientUserModel->id;
                    $model->sick_time = $hissPatient['first_in_time'];
                    $model->main_desc = $hissPatientDetailData['patient_tell'];
                    $model->now_medical_history = $hissPatientDetailData['case_history_now'];
                    $model->auxiliary_result = $hissPatientDetailData['assist_inspect'];

                    $model->jw_history = '';    // 既往史
                    $model->person_history = '';    // 个人史
                    $model->family_history = $hissPatientDetailData['family_history'];
                    $model->physique_history = $hissPatientDetailData['body_inspect'];
                    $model->diagnose = '';  // 诊断

                    $model->patient_diseases_id = $patientUserModel->patient_diseases_id;
                    $model->diseases_name = (string)PatientDiseases::find()->where(['id' => $patientUserModel->patient_diseases_id])->select('diseases_name')->scalar();
                    if (!$model->save()) {
                        throw new \Exception(json_encode($model->errors), 500);
                    }
                }
                $transaction->commit();
            } catch (\Exception $exception) {
                $transaction->rollBack();
                throw new \Exception($exception->getLine() . $exception->getMessage(), 500);
            }
            echo $patientUserModel->id . PHP_EOL;
        }
        file_put_contents($fileName, '*********************项目：' . $projectId . '  END  ***********************' . PHP_EOL . PHP_EOL, FILE_APPEND);
    }


    /**
     * 修复数据
     *
     * @param int $projectId
     * @throws \Exception
     * @author wangxiang
     */
    public static function repairPatient(int $projectId)
    {
        self::$projectId = $projectId;
        $transaction = Yii::$app->db->beginTransaction();
        try {
            switch ($projectId) {
                case ConfigService::PROJECT['hy']:
                    $baiyouData = User::find()->where(['project_id' => self::$projectId])->orderBy('id')->select('patient_card_id')->asArray()->column();
                    foreach ($baiyouData as $patientCardId) {
                        // 处理患者主表数据
                        Model::setTableName('jg_patient_info');
                        $hissPatient = Model::find()->where(['treat_number' => $patientCardId])->orderBy('show DESC')->asArray()->one();
                        if (!$hissPatient) {
                            continue;
                        }

                        $transaction = Yii::$app->db->beginTransaction();
                        try {
                            $patientUserModel = User::find()->where(['project_id' => self::$projectId, 'patient_card_id' => $patientCardId])->one();

                            Model::setTableName('jg_patient_follow');
                            $hissFollowOne = Model::find()->where(['patient_id' => $hissPatient['patient_id']])->orderBy('follow_time DESC')->asArray()->one();
                            if ($hissFollowOne) {
                                if ($hissFollowOne['type'] == 1) {
                                    // 医助
                                    if (!$patientUserModel->yz_last_callback_time) {
                                        $patientUserModel->yz_last_callback_time = $hissFollowOne['follow_time'];
                                        if (!$patientUserModel->save()) {
                                            throw new \Exception(json_encode($patientUserModel->errors), 500);
                                        }
                                    }
                                } else if ($hissFollowOne['type'] == 2) {
                                    // 客服
                                    if (!$patientUserModel->kf_last_callback_time) {
                                        $patientUserModel->kf_last_callback_time = $hissFollowOne['follow_time'];
                                        if (!$patientUserModel->save()) {
                                            throw new \Exception(json_encode($patientUserModel->errors), 500);
                                        }
                                    }
                                }
                            }

                            $transaction->commit();
                        } catch (\Exception $exception) {
                            $transaction->rollBack();
                            throw new \Exception($exception->getLine() . $exception->getMessage(), 500);
                        }

                        echo $patientUserModel->id . PHP_EOL;
                    }
                    break;
                case ConfigService::PROJECT['bd']:
                    /*$baiyouData = User::find()->where(['project_id' => self::$projectId])->select(['patient_card_id'])->orderBy('id')->asArray()->column();
                    foreach ($baiyouData as $patientCardId) {
                        Model::setTableName('jg_patient_info');
                        $hissPatient = Model::find()->where(['treat_number' => $patientCardId])->asArray()->one();
                        if (!$hissPatient) {
                            continue;
                        }

                        $transaction = Yii::$app->db->beginTransaction();
                        try {
                            $patientUserModel = User::find()->where(['project_id' => self::$projectId, 'patient_card_id' => $patientCardId])->one();
                            $consultRoomId = ConfigService::CLINIC[self::$projectId][$hissPatient['consult_room_id']] ?? 0;
                            $consultRoomId && $patientUserModel->clinic_id = $consultRoomId;
                            if ($consultRoomId != 10) { // 如果不是六诊， 则更新医助
                                $assistantData = self::getMemberByHissUserId($hissPatient['handle_id']);
                                $belongAssistantId = $assistantData['id'] ?? 0;
                                if ($hissPatient['handle_id'] && $belongAssistantId) {
                                    $patientUserModel->belong_assistant_id = $belongAssistantId;
                                }
                            }
                            if (!$patientUserModel->save()) {
                                throw new \Exception(json_encode($patientUserModel->errors), 500);
                            }
                            $transaction->commit();

                            echo $patientUserModel->id . PHP_EOL;
                        } catch (\Exception $exception) {
                            $transaction->rollBack();
                            throw new \Exception($exception->getLine() . $exception->getMessage(), 500);
                        }

                    }*/

                    // 将吴晶晶（112）下的数据给臧雪梅（127）
                    User::updateAll(['belong_assistant_id' => 127], ['belong_assistant_id' => 112, 'project_id' => $projectId]);

                    break;
                case ConfigService::PROJECT['wz']:
                    // 医助胡丽萍改成三诊  对应member_id为281
                    Attr::updateAll(['clinic_id' => 28], ['member_id' => 281, 'project_id' => $projectId]);

                    // 把胡丽萍（281） 下面的患者给 何倩（287）
                    User::updateAll(['belong_assistant_id' => 287], ['belong_assistant_id' => 281, 'project_id' => $projectId]);

                    // 将医助名为三诊（283）的下面数据平均分配给两个医助下（287，289）
                    $patientIdData = User::find()->where(['belong_assistant_id' => 283, 'project_id' => $projectId])->select('id')->asArray()->column();
                    if (!$patientIdData) {
                        break;
                    }
                    shuffle($patientIdData);
                    $flag = ceil(count($patientIdData) / 2);
                    $newPatientIdData = array_chunk($patientIdData, $flag);
                    if (isset($newPatientIdData[0]) && $newPatientIdData[0]) {
                        User::updateAll(['belong_assistant_id' => 287], ['id' => $newPatientIdData[0], 'project_id' => $projectId]);
                    }

                    if (isset($newPatientIdData[1]) && $newPatientIdData[1]) {
                        User::updateAll(['belong_assistant_id' => 289], ['id' => $newPatientIdData[1], 'project_id' => $projectId]);
                    }

                    // 将医助名为一诊（286）的数据直接分给肖倩（293）
                    User::updateAll(['belong_assistant_id' => 293], ['belong_assistant_id' => 286, 'project_id' => $projectId]);
                    break;
                case ConfigService::PROJECT['nb']:
                    // 朱婉（186）的和朱荣荣（181）的数据分给一诊（182）
                    User::updateAll(['belong_assistant_id' => 182], ['belong_assistant_id' => [181, 186], 'project_id' => $projectId]);
                    break;

                case ConfigService::PROJECT['nt']:
                    // 戴伟（309）的，5条给冒亚娟（312）
                    User::updateAll(['belong_assistant_id' => 312], ['belong_assistant_id' => 309, 'project_id' => $projectId]);
                    break;
                case ConfigService::PROJECT['gz']:
                    // 戴伟（327）的数据给詹燕（375）
                    User::updateAll(['belong_assistant_id' => 375], ['belong_assistant_id' => 327, 'project_id' => $projectId]);

                    // 肖海燕（329）的数据给杜玲茜（325）
                    User::updateAll(['belong_assistant_id' => 325], ['belong_assistant_id' => 329, 'project_id' => $projectId]);
                    break;
                default:

            }
            $transaction->commit();
        } catch (\Exception $exception) {
            $transaction->rollBack();
            throw new \Exception($exception->getMessage(), 500);
        }

    }


    /**
     * 根据hiss中的员工id获取白友中的员工信息
     *
     * @param int $userId
     * @return array|Member|\yii\db\ActiveRecord|null
     * @author wangxiang
     */
    private static function getMemberByHissUserId(int $userId)
    {
        Model::setTableName('jg_user');
        $unionId = Model::find()->where(['id' => $userId])->select('union_id')->scalar();
        $data = Member::find()
            ->alias('m')
            ->leftJoin(Attr::tableName() . ' attr', 'm.id = attr.member_id')
            ->leftJoin(Department::tableName() . ' d', 'd.id = attr.department_id')
            ->where(['m.ding_unionid' => $unionId])
            ->andWhere(['attr.project_id' => self::$projectId])
            ->select(['m.*', 'attr.department_id', 'd.name as department_name', 'attr.profession_id', 'attr.profession_name'])
            ->asArray()->one();

        return $data;
    }


    /**
     * 记录hiss和白友手机号不相同患者
     *
     * @param int $projectId
     * @author wangxiang
     */
    public static function tel(int $projectId)
    {
        self::$projectId = $projectId;
        $baiyouData = User::find()->where(['project_id' => self::$projectId])->select(['id', 'patient_card_id', 'name', 'mobile'])->orderBy('id')->asArray()->all();
        foreach ($baiyouData as $list) {
            Model::setTableName('jg_patient_info');
            $hissPatient = Model::find()->where(['treat_number' => $list['patient_card_id']])->asArray()->one();
            if ($hissPatient && $hissPatient['tel'] && $hissPatient['tel'] != '--' && $hissPatient['tel'] != $list['mobile']) {
                //file_put_contents('/data/wwwlogs/hiss_patient_mobile_record.txt', $list['name'] . '《==》' . $list['patient_card_id'] . '《==》白友手机号：' .  $list['mobile'] . '《==》hiss手机号：' .  $hissPatient['tel'] . PHP_EOL, FILE_APPEND);
                file_put_contents($projectId . '-tel.txt', $list['name'] . '《==》' . $list['patient_card_id'] . '《==》白友手机号：' . $list['mobile'] . '《==》hiss手机号：' . $hissPatient['tel'] . PHP_EOL, FILE_APPEND);
            }
            echo $list['id'] . PHP_EOL;
        }
    }


    /**
     * 修改手机号
     *
     * @param int $projectId
     * @author wangxiang
     */
    public static function changeTel(int $projectId)
    {
        self::$projectId = $projectId;
        $baiyouData = User::find()->where(['project_id' => self::$projectId])->select(['id', 'patient_card_id', 'name', 'mobile'])->orderBy('id')->asArray()->all();
        foreach ($baiyouData as $list) {
            Model::setTableName('jg_patient_info');
            $hissPatient = Model::find()->where(['treat_number' => $list['patient_card_id']])->asArray()->one();

            if ($hissPatient && $hissPatient['tel'] && $hissPatient['tel'] != '--' && $hissPatient['tel'] != $list['mobile']) {
                // 判断手机号是否为正常的
                if (preg_match("/^1[3456789]{1}\d{9}$/", $hissPatient['tel'])) {
                    $patientUserModel = User::find()->where(['project_id' => self::$projectId, 'patient_card_id' => $list['patient_card_id']])->one();
                    $patientUserModel->mobile = $hissPatient['tel'];
                    if (!$patientUserModel->save()) {
                        file_put_contents('tel.txt', $list['name'] . '《==》' . $list['patient_card_id'] . '《==》白友手机号：' . $list['mobile'] . '《==》hiss手机号：' . $hissPatient['tel'] . PHP_EOL, FILE_APPEND);
                    }
                } else {
                    file_put_contents('tel.txt', $list['name'] . '《==》' . $list['patient_card_id'] . '《==》白友手机号：' . $list['mobile'] . '《==》hiss手机号：' . $hissPatient['tel'] . PHP_EOL, FILE_APPEND);
                }
            }
            echo $list['id'] . PHP_EOL;
            /*if ($hissPatient && $hissPatient['tel'] && $hissPatient['tel'] != '--' && $hissPatient['tel'] != $list['mobile']) {
                file_put_contents('/data/wwwlogs/hiss_patient_mobile_record.txt', $list['name'] . '《==》' . $list['patient_card_id'] . '《==》白友手机号：' .  $list['mobile'] . '《==》hiss手机号：' .  $hissPatient['tel'] . PHP_EOL, FILE_APPEND);
                //file_put_contents($projectId . '-tel.txt', $list['name'] . '《==》' . $list['patient_card_id'] . '《==》白友手机号：' .  $list['mobile'] . '《==》hiss手机号：' .  $hissPatient['tel'] . PHP_EOL, FILE_APPEND);
            }
            echo $list['id'] . PHP_EOL;*/
        }
    }


    /**
     * 修复北大数据
     *
     * @param int $projectId
     * @throws \Exception
     * @author wangxiang
     */
    public static function changeData(int $projectId)
    {
        self::$projectId = $projectId;
        $baiyouData = User::find()->where(['project_id' => self::$projectId])->select(['patient_card_id'])->orderBy('id')->asArray()->column();
        foreach ($baiyouData as $patientCardId) {
            Model::setTableName('jg_patient_info');
            $hissPatient = Model::find()->where(['treat_number' => $patientCardId])->asArray()->one();
            if (!$hissPatient) {
                continue;
            }

            $transaction = Yii::$app->db->beginTransaction();
            try {
                $patientUserModel = User::find()->where(['project_id' => self::$projectId, 'patient_card_id' => $patientCardId])->one();
                $consultRoomId = ConfigService::CLINIC[self::$projectId][$hissPatient['consult_room_id']] ?? 0;
                $consultRoomId && $patientUserModel->clinic_id = $consultRoomId;
                if ($consultRoomId != 10) { // 如果不是六诊， 则更新医助
                    $assistantData = self::getMemberByHissUserId($hissPatient['handle_id']);
                    $belongAssistantId = $assistantData['id'] ?? 0;
                    if ($hissPatient['handle_id'] && $belongAssistantId) {
                        $patientUserModel->belong_assistant_id = $belongAssistantId;
                    }
                }
                if (!$patientUserModel->save()) {
                    throw new \Exception(json_encode($patientUserModel->errors), 500);
                }
                $transaction->commit();

                echo $patientUserModel->id . PHP_EOL;
            } catch (\Exception $exception) {
                $transaction->rollBack();
                throw new \Exception($exception->getLine() . $exception->getMessage(), 500);
            }

        }
    }


    public static function test(int $projectId)
    {
        self::$projectId = $projectId;
        $baiyouData = User::find()->where(['project_id' => self::$projectId])->orderBy('id')->select('patient_card_id')->asArray()->column();
        foreach ($baiyouData as $patientCardId) {
            Model::setTableName('jg_patient_info');
            $hissPatient = Model::find()->where(['treat_number' => $patientCardId])->asArray()->one();
            if (!$hissPatient) {
                continue;
            }

            $transaction = Yii::$app->db->beginTransaction();
            try {
                $patientUserModel = User::find()->where(['project_id' => self::$projectId, 'patient_card_id' => $patientCardId])->one();
                $consultRoomId = ConfigService::CLINIC[self::$projectId][$hissPatient['consult_room_id']] ?? 0;
                $consultRoomId && $patientUserModel->clinic_id = $consultRoomId;
                $assistantData = self::getMemberByHissUserId($hissPatient['handle_id']);
                $belongAssistantId = $assistantData['id'] ?? 0;
                if ($hissPatient['handle_id'] && $belongAssistantId) {
                    $patientUserModel->belong_assistant_id = $belongAssistantId;
                }
                if (!$patientUserModel->save()) {
                    throw new \Exception(json_encode($patientUserModel->errors), 500);
                }
                $transaction->commit();

                echo $patientUserModel->id . PHP_EOL;
            } catch (\Exception $exception) {
                $transaction->rollBack();
                throw new \Exception($exception->getLine() . $exception->getMessage(), 500);
            }
        }


        /*  Model::setTableName('jg_patient_follow');
          $yzFollowUser = (string) Model::find()
              ->alias('f')
              ->leftJoin('jg_user', 'jg_user.id = f.follow_user')
              ->where(['f.patient_id' => '9566', 'f.type' => 2])
              ->orderBy('f.follow_time DESC')
              ->select(['jg_user.user_name'])
              ->scalar();
          print_r($yzFollowUser);exit;*/


        /*echo 'test';exit;
        self::$projectId = $projectId;
        $cardIdData = [
            '9904108', '7910109'
        ];

        foreach ($cardIdData as $patientCardId) {
            Model::setTableName('jg_patient_info');
            $hissPatient = Model::find()->where(['treat_number' => $patientCardId])->asArray()->one();
            $patientUserModel = User::find()->where(['patient_card_id' => $patientCardId])->one();
            // 处理患者回访数据
            Model::setTableName('jg_patient_follow');
            $hissFollowData = Model::find()->where(['patient_id' => $hissPatient['patient_id']])->asArray()->all();
            $followInsertData = [];
            foreach ($hissFollowData as $list) {
                $flag = Callback::find()->where(['project_id' => self::$projectId, 'patient_user_id' => $patientUserModel->id, 'current_callback_time' => $list['follow_time']])->exists();
                if ($flag) {
                    continue;
                }
                $memberInfo = self::getMemberByHissUserId($list['follow_user']);
                $followInsertData[] = [
                    'project_id' => self::$projectId,
                    'patient_user_id' => $patientUserModel->id,
                    'callback_state_id' => ConfigService::FOLLOW_RESULT[self::$projectId]['id'][$list['follow_result']] ?? 0,
                    'callback_state' => ConfigService::FOLLOW_RESULT[self::$projectId]['title'][$list['follow_result']] ?? '',
                    'callback_way_id' => ConfigService::FOLLOW_TYPE[self::$projectId][$list['follow_type']] ?? 4,
                    'content' => $list['follow'],
                    'current_callback_time' => (int) $list['follow_time'],
                    'outpatient_type_id' => $patientUserModel->outpatient_type_id,
                    'next_callback_time' => $patientUserModel->next_callback_time,
                    'next_fuzhen_time' => $hissPatient['order_time'],
                    'member_id' => $memberInfo['id'] ?? 0,
                    'member_name' => $memberInfo['realname'] ?? '',
                    'member_departmement' => $memberInfo['department_name'] ?? '',
                    'created_at' => (int) $list['follow_time'],
                    'updated_at' => (int) $list['follow_time']
                ];
            }
            $followInsertData && Yii::$app->db->createCommand()->batchInsert(Callback::tableName(),
                ['project_id', 'patient_user_id', 'callback_state_id', 'callback_state', 'callback_way_id',
                    'content', 'current_callback_time', 'outpatient_type_id', 'next_callback_time',
                    'next_fuzhen_time', 'member_id', 'member_name', 'member_departmement', 'created_at', 'updated_at'
                ], $followInsertData)->execute();
        }*/
    }


    /**
     * 长沙回访数据补漏
     *
     * @throws \yii\db\Exception
     * @author wangxiang
     */
    public static function changeCs()
    {
        self::$projectId = ConfigService::PROJECT['cs'];
        Model::setTableName('jg_patient_follow');
        $hissFollowData = Model::find()
            ->where(['>=', 'follow_time', 1586620800])
            ->asArray()
            ->all();

        $patientIdData = array_column($hissFollowData, 'patient_id');
        Model::setTableName('jg_patient_info');
        $patientData = Model::find()
            ->where(['patient_id' => $patientIdData])
            ->select(['treat_number', 'patient_id', 'order_time'])
            ->asArray()
            ->all();
        foreach ($patientData as $item) {
            $patientCardId = $item['treat_number'];
            $patientUserModel = User::find()->where(['project_id' => self::$projectId, 'patient_card_id' => $patientCardId])->one();
            if (!$patientUserModel) {
                continue;
            }
            // 处理患者回访数据
            Model::setTableName('jg_patient_follow');
            $hissFollowData = Model::find()->where(['patient_id' => $item['patient_id']])->asArray()->all();
            $followInsertData = [];
            foreach ($hissFollowData as $list) {
                $flag = Callback::find()->where(['project_id' => self::$projectId, 'patient_user_id' => $patientUserModel->id, 'current_callback_time' => $list['follow_time']])->exists();
                if ($flag) {
                    continue;
                }
                $memberInfo = self::getMemberByHissUserId($list['follow_user']);
                $followInsertData[] = [
                    'project_id' => self::$projectId,
                    'patient_user_id' => $patientUserModel->id,
                    'callback_state_id' => ConfigService::FOLLOW_RESULT[self::$projectId]['id'][$list['follow_result']] ?? 0,
                    'callback_state' => ConfigService::FOLLOW_RESULT[self::$projectId]['title'][$list['follow_result']] ?? '',
                    'callback_way_id' => ConfigService::FOLLOW_TYPE[self::$projectId][$list['follow_type']] ?? 4,
                    'content' => $list['follow'],
                    'current_callback_time' => (int)$list['follow_time'],
                    'outpatient_type_id' => $patientUserModel->outpatient_type_id,
                    'next_callback_time' => $patientUserModel->next_callback_time,
                    'next_fuzhen_time' => $item['order_time'],
                    'member_id' => $memberInfo['id'] ?? 0,
                    'member_name' => $memberInfo['realname'] ?? '',
                    'member_departmement' => $memberInfo['department_name'] ?? '',
                    'created_at' => (int)$list['follow_time'],
                    'updated_at' => (int)$list['follow_time']
                ];
            }

            $followInsertData && Yii::$app->db->createCommand()->batchInsert(Callback::tableName(),
                ['project_id', 'patient_user_id', 'callback_state_id', 'callback_state', 'callback_way_id',
                    'content', 'current_callback_time', 'outpatient_type_id', 'next_callback_time',
                    'next_fuzhen_time', 'member_id', 'member_name', 'member_departmement', 'created_at', 'updated_at'
                ], $followInsertData)->execute();
        }


        /* // 处理患者回访数据
         Model::setTableName('jg_patient_follow');
         $hissFollowData = Model::find()
             ->where(['>=', 'follow_time', 1586620800])
             ->asArray()
             ->all();
         $patientIdData = [];
         $followUserIdData = [];
         foreach ($hissFollowData as $item) {
             $patientIdData[] = $item['patient_id'];
             $followUserIdData[] = $item['follow_user'];
         }
         Model::setTableName('jg_user');
         $unionIdData = [];
         $unionIdData = Model::find()->where(['user_id' => $followUserIdData]);

         foreach ( as $list) {
             $flag = Callback::find()->where(['project_id' => self::$projectId, 'patient_user_id' => $patientUserModel->id, 'current_callback_time' => $list['follow_time']])->exists();
             if ($flag) {
                 continue;
             }
         }


         $followInsertData = [];
         foreach ($hissFollowData as $list) {
             $flag = Callback::find()->where(['project_id' => self::$projectId, 'patient_user_id' => $patientUserModel->id, 'current_callback_time' => $list['follow_time']])->exists();
             if ($flag) {
                 continue;
             }
             $memberInfo = self::getMemberByHissUserId($list['follow_user']);
             $followInsertData[] = [
                 'project_id' => self::$projectId,
                 'patient_user_id' => $patientUserModel->id,
                 'callback_state_id' => ConfigService::FOLLOW_RESULT[self::$projectId]['id'][$list['follow_result']] ?? 0,
                 'callback_state' => ConfigService::FOLLOW_RESULT[self::$projectId]['title'][$list['follow_result']] ?? '',
                 'callback_way_id' => ConfigService::FOLLOW_TYPE[self::$projectId][$list['follow_type']] ?? 4,
                 'content' => $list['follow'],
                 'current_callback_time' => (int) $list['follow_time'],
                 'outpatient_type_id' => $patientUserModel->outpatient_type_id,
                 'next_callback_time' => $patientUserModel->next_callback_time,
                 'next_fuzhen_time' => $hissPatient['order_time'],
                 'member_id' => $memberInfo['id'] ?? 0,
                 'member_name' => $memberInfo['realname'] ?? '',
                 'member_departmement' => $memberInfo['department_name'] ?? '',
                 'created_at' => (int) $list['follow_time'],
                 'updated_at' => (int) $list['follow_time']
             ];
         }*/
    }


    /**
     * 修复患者表上次回访人信息
     * @author wangxiang
     */
    public static function repairCallbackInfo()
    {
        $projectIdData = [
            1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
        ];

        $errorPatientIdData = [];

        foreach ($projectIdData as $projectId) {
            $patientIdData = User::find()->where(['project_id' => $projectId])->orderBy('id')->select('id')->column();
            foreach ($patientIdData as $patientId) {
                try {
                    $model = User::findOne($patientId);

                    $kfCallbackInfo = self::_getCallbackInfo($patientId, 1);
                    $yzCallbackInfo = self::_getCallbackInfo($patientId, 2);

                    $kfCallbackInfo && $model->kf_last_callback_id = $kfCallbackInfo['member_id'];
                    $kfCallbackInfo && $model->kf_last_callback_user = $kfCallbackInfo['member_name'];
                    $kfCallbackInfo && $model->kf_last_callback_time = $kfCallbackInfo['current_callback_time'];

                    $yzCallbackInfo && $model->yz_last_callback_id = $yzCallbackInfo['member_id'];
                    $yzCallbackInfo && $model->yz_last_callback_user = $yzCallbackInfo['member_name'];
                    $yzCallbackInfo && $model->yz_last_callback_time = $yzCallbackInfo['current_callback_time'];

                    if (!$model->save()) {
                        $errorPatientIdData[] = $patientId;
                    }
                } catch (\Exception $exception) {
                    $errorPatientIdData[] = $patientId;
                    continue;
                }

                echo $projectId . '-' . $patientId . PHP_EOL;
            }
        }

        return $errorPatientIdData;
    }


    /**
     * @param int $patientId
     * @param int $type 1：客服， 2：医助
     * @return array|\yii\db\ActiveRecord|null
     * @author wangxiang
     */
    private static function _getCallbackInfo(int $patientId, int $type)
    {
        $query = Callback::find()
            ->alias('c')
            ->leftJoin(Attr::tableName() . ' attr', 'attr.member_id = c.member_id')
            ->where([
                'c.patient_user_id' => $patientId
            ]);
        if ($type == 1) {
            // 客服
            $query = $query->andWhere(['attr.profession_id' => Profession::ID_CUSTOMER]);
        } else if ($type == 2) {
            // 医助
            $query = $query->andWhere(['attr.profession_id' => Profession::ID_MEDICAL]);
        }

        return $query
            ->select(['c.member_id', 'c.member_name', 'c.current_callback_time'])
            ->orderBy('c.current_callback_time DESC')
            ->asArray()
            ->one();
    }

    /**
     * 海口项目数据从hiss迁移到白友
     *
     * @author chenyuebin
     * @param int $projectId
     * @throws \Exception
     */
    public static function hissToBy(int $projectId)
    {
        $fileName = '/data/wwwlogs/hiss_patient_mobile_record_hk.txt';
//        $fileName = '/home/www/hcrm/backend/web/test.txt';
        self::$projectId = $projectId;
        // $baiyouData = User::find()->where(['project_id' => self::$projectId])->orderBy('id')->select('patient_card_id')->asArray()->column();
        file_put_contents($fileName, '*********************项目：' . $projectId . '  START ***********************' . PHP_EOL, FILE_APPEND);

        Model::setTableName('jg_patient_info');
        $hissData = Model::find()->orderBy('show DESC')->asArray()->all();
        foreach ($hissData as $hissPatient) {
            $transaction = Yii::$app->db->beginTransaction();
            try {
                // 处理患者主表数据
                $patientUserModel = User::find()->where(['project_id' => self::$projectId, 'patient_card_id' => $hissPatient['treat_number']])->one();
                if (!$patientUserModel) {
                    $patientUserModel = new User();
                }

                $patientUserModel->name = trim($hissPatient['name']);
                $patientUserModel->project_id = self::$projectId;
                $patientUserModel->patient_card_id = $hissPatient['treat_number'];
                $patientUserModel->birthday = ((date('Y') - $hissPatient['age']) . '-00-00');
                $patientUserModel->age = $hissPatient['age'];
                $patientUserModel->wx_name = $hissPatient['weixin'];
                $patientUserModel->source_channel_id = ConfigService::SOURCE_CHANNEL[self::$projectId][$hissPatient['qudao_id']] ?? 0;
                $patientUserModel->gender = $hissPatient['sex'];

                if ($hissPatient && $hissPatient['tel'] && $hissPatient['tel'] != '--' && $hissPatient['tel'] != $patientUserModel->mobile) {
                    // 判断手机号是否为正常的
                    if (preg_match("/^1[3456789]{1}\d{9}$/", $hissPatient['tel'])) {
                        $patientUserModel->mobile = $hissPatient['tel'];
                    } else {
                        file_put_contents($fileName, $patientUserModel->name . '《==》' . $hissPatient['treat_number'] . '《==》白友手机号：' . $patientUserModel->mobile . '《==》hiss手机号：' . $hissPatient['tel'] . PHP_EOL, FILE_APPEND);
                    }
                }

                /*if (!$patientUserModel->mobile && $hissPatient['tel'] && $hissPatient['tel'] != '--') {
                    $telData = explode('/', $hissPatient['tel']);
                    (isset($telData[0]) && $telData[0]) && $patientUserModel->mobile = $telData[0];
                    if (count($telData) > 1) {
                        unset($telData[0]);
                        $patientUserModel->remark = implode('/', $telData);
                    }
                }*/

                if (!$patientUserModel->city_id && $hissPatient['city']) {
                    $city = Provinces::find()->where(['level' => Provinces::LEVEL_CITY, 'title' => $hissPatient['city']])->one();
                    $city && $patientUserModel->city_id = $city->id;
                }

                (!$patientUserModel->city_name && $hissPatient['city']) && $patientUserModel->city_name = $hissPatient['city'];
                !$patientUserModel->address && $patientUserModel->address = $hissPatient['address'];

                // 病种
                $patientUserModel->patient_diseases_id = ConfigService::PATIENT_DISEASES[self::$projectId][$hissPatient['ill_type']]['parent'] ?? 0;
                $patientUserModel->patient_diseases_child_id = ConfigService::PATIENT_DISEASES[self::$projectId][$hissPatient['ill_type']]['child'] ?? 0;

                /*处理医助归属人和客服归属人开始*/
                $assistantData = self::getMemberByHissUserId($hissPatient['handle_id']);
                $customerData = self::getMemberByHissUserId($hissPatient['customer_id']);
                $belongAssistantId = $assistantData['id'] ?? 0;
                if ($hissPatient['handle_id'] && $belongAssistantId) {
                    // 处理医助， 如果是北大项目且诊室不为六诊或不是北大的项目， 才更新
                    $consultRoomId = ConfigService::CLINIC[self::$projectId][$hissPatient['consult_room_id']] ?? 0;
                    if (self::$projectId != ConfigService::PROJECT['bd'] || $consultRoomId != 10) {
                        $patientUserModel->belong_assistant_id = $belongAssistantId;
                    }
                }

                if ($hissPatient['customer_id']) {
                    $patientUserModel->belong_member_id = $customerData['id'] ?? 0;
                    $patientUserModel->belong_member_name = $customerData['realname'] ?? '';
                }

                /*处理医助归属人和客服归属人结束*/

                /*处理治疗类型开始*/
                $effectTypeId_1 = ConfigService::EFFECT_TYPE[self::$projectId]['hiss_fz'][$hissPatient['state']] ?? 0;
                $effectTypeId_2 = ConfigService::EFFECT_TYPE[self::$projectId]['hiss_zl'][$hissPatient['treat_type']] ?? 0;

                $riskTypeId_1 = ConfigService::RISK_TYPE[self::$projectId]['hiss_fz'][$hissPatient['state']] ?? 0;
                $riskTypeId_2 = ConfigService::RISK_TYPE[self::$projectId]['hiss_zl'][$hissPatient['treat_type']] ?? 0;

                $clinicAssessId_1 = ConfigService::CLINIC_ASSESS[self::$projectId]['hiss_fz'][$hissPatient['state']] ?? 0;
                $clinicAssessId_2 = ConfigService::CLINIC_ASSESS[self::$projectId]['hiss_zl'][$hissPatient['treat_type']] ?? 0;


                // 就诊类型
                $outpatientTypeId_1 = ConfigService::OUTPATIENT_TYPE[self::$projectId]['hiss_fz'][$hissPatient['state']] ?? 0;
                $patientUserModel->outpatient_type_id = $outpatientTypeId_1;
                if (in_array($hissPatient['state'], [4, 7])) {// 如果复诊类型为抗复发或治愈，则添加康复发标识
                    $patientUserModel->is_anti_relapse = 1;
                }
                //$outpatientTypeId_2 = ConfigService::OUTPATIENT_TYPE[self::$projectId]['hiss_zl'][$hissPatient['treat_type']] ?? 0;
                /*if (!in_array(self::$projectId, [ConfigService::PROJECT['bd'], ConfigService::PROJECT['gz'], ConfigService::PROJECT['cs']])) {
                    if ($outpatientTypeId_1 || $outpatientTypeId_2) {
                        $patientUserModel->outpatient_type_id = $outpatientTypeId_1 ? : $outpatientTypeId_2;
                    }
                }*/

                $patientUserModel->effect_type_id = $effectTypeId_1 ?: $effectTypeId_2;
                $patientUserModel->risk_type_id = $riskTypeId_1 ?: $riskTypeId_2;
                $patientUserModel->clinic_assess_id = $clinicAssessId_1 ?: $clinicAssessId_2;
                if ($hissPatient['state'] == 8) {// 如果复诊类型为敏感，则对应风控类型为敏感
                    $patientUserModel->risk_type_id = 51;
                }

                $isAntiRelapse_1 = in_array($hissPatient['state'], ConfigService::IS_ANTI_RELAPSE[self::$projectId]['hiss_fz']);
                $isAntiRelapse_2 = in_array($hissPatient['treat_type'], ConfigService::IS_ANTI_RELAPSE[self::$projectId]['hiss_zl']);
                $patientUserModel->is_anti_relapse = ($isAntiRelapse_1 || $isAntiRelapse_2) ? 1 : 0;
                /*处理治疗类型结束*/

                // 取患者最后一次的治疗时间
                Model::setTableName('jg_treat');
                $lastClinicTime = (int)Model::find()->where(['patient_id' => $hissPatient['patient_id']])->orderBy('add_time DESC')->select('add_time')->scalar();
                $patientUserModel->last_clinic_time = $lastClinicTime;

                if (in_array(self::$projectId, [ConfigService::PROJECT['nc'], ConfigService::PROJECT['nt'], ConfigService::PROJECT['nb'], ConfigService::PROJECT['bd'], ConfigService::PROJECT['hk']])) {
                    $patientUserModel->clinic_id = ConfigService::CLINIC[self::$projectId][$hissPatient['consult_room_id']] ?? 0;
                } else {
                    $patientUserModel->clinic_id = ConfigService::CLINIC[self::$projectId][$hissPatient['consult_room_id']] ?? 0;
                }
                $patientUserModel->profession = $hissPatient['job'] ?? '';

                // 判断hiss那边的下次回访时间是否有, 如果没有则取当前时间后两天
                $nextCallbackTime = $hissPatient['next_follow_time'];
                if (!$nextCallbackTime) {
                    $nextCallbackTime = (int)strtotime("+2 days");
                }
                $patientUserModel->yz_next_callback_time = $nextCallbackTime;
                $patientUserModel->yz_last_callback_time = $hissPatient['last_follow_time'];
                if (in_array($hissPatient['state'], ConfigService::DIAGNOSIS[self::$projectId])) {
                    // 如果该患者在hiss中是断诊状态时
                    $patientUserModel->kf_next_callback_time = $nextCallbackTime;
                    $patientUserModel->kf_last_callback_time = $hissPatient['last_follow_time'];
                }

                // 针对修复数据， 取回访记录中的数据中最后一次回访时间， 如果是客服回访的则更新客服， 如果是医助回访的则更新自助
                if (in_array(self::$projectId, [ConfigService::PROJECT['hy']])) {
                    Model::setTableName('jg_patient_follow');
                    $hissFollowOne = Model::find()->where(['patient_id' => $hissPatient['patient_id']])->orderBy('follow_time DESC')->asArray()->one();
                    if ($hissFollowOne['type'] == 1) {
                        // 医助
                        $patientUserModel->yz_last_callback_time = $hissFollowOne['follow_time'];
                    } else if ($hissFollowOne['type'] == 2) {
                        // 客服
                        $patientUserModel->kf_last_callback_time = $hissFollowOne['follow_time'];
                    }
                }

                //$patientUserModel->last_callback_time = $hissPatient['last_follow_time'];   // 上次回访日期     作废
                //$patientUserModel->next_callback_time = $hissPatient['next_follow_time'];   // 下次回访日期     作废

                $patientUserModel->last_revisiting_time = $hissPatient['last_in_time']; // 上次到诊日期
                $patientUserModel->next_revisiting_time = $hissPatient['order_time']; // 下次复诊日期

                // 处理患者上次回访的医助和客服
                Model::setTableName('jg_patient_follow');
                $yzFollowUser = (string)Model::find()
                    ->alias('f')
                    ->leftJoin('jg_user', 'jg_user.id = f.follow_user')
                    ->where(['f.patient_id' => $hissPatient['patient_id'], 'f.type' => 1])
                    ->orderBy('f.follow_time DESC')
                    ->select('jg_user.user_name')
                    ->scalar();

                $kfFollowUser = (string)Model::find()
                    ->alias('f')
                    ->leftJoin('jg_user', 'jg_user.id = f.follow_user')
                    ->where(['f.patient_id' => $hissPatient['patient_id'], 'f.type' => 2])
                    ->orderBy('f.follow_time DESC')
                    ->select('jg_user.user_name')
                    ->scalar();

                $patientUserModel->kf_last_callback_user = $kfFollowUser;
                $patientUserModel->yz_last_callback_user = $yzFollowUser;

                // 获取回访次数
                Model::setTableName('jg_patient_follow');
                $callbackCount = Model::find()->where(['patient_id' => $hissPatient['patient_id']])->count();
                $patientUserModel->yz_callback_count = $callbackCount;

                // 获取来院次数
                Model::setTableName('jg_patient_record');
                $revisitingCount = Model::find()
                    ->where(['patient_id' => $hissPatient['patient_id']])
                    ->groupBy(['UNIX_TIMESTAMP(FROM_UNIXTIME(`in_time`, "%Y-%m-%d"))'])
                    ->count();
                $patientUserModel->revisiting_count = $revisitingCount;

                /*// 获取患者的导诊数据
                Model::setTableName('jg_patient_record');
                $firstInTime = (int) Model::find()->where(['patient_id' => $hissPatient['patient_id']])->orderBy('in_time ASC')->select('in_time')->scalar();
                if ($firstInTime) {
                    // 获取当月时间结束点
                    $d = date('t', $firstInTime);
                    $endTime = mktime(23,59,59, date('m', $firstInTime), $d, date('Y', $firstInTime));
                    $revisitingCount = Model::find()->where(['patient_id' => $hissPatient['patient_id']])->andWhere(['>', 'in_time', $endTime])->count();
                    $patientUserModel->revisiting_count = $revisitingCount;
                }*/

                /*if ($patientUserModel->remark) {
                    $patientUserModel->remark .= ',' . $hissPatient['remark'];
                } else {
                    $patientUserModel->remark = $hissPatient['remark'];
                }*/
                // 备注，如果患者表无备注内容，则从备注表获取最新一条备注内容
                if ($hissPatient['remark']) {
                    $patientUserModel->remark = $hissPatient['remark'];
                } else {
                    Model::setTableName('jg_patient_remark');
                    $hissRemark = Model::find()
                        ->select(['remark'])
                        ->where([
                            'patient_id' => $hissPatient['patient_id'],
                        ])
                        ->andWhere([
                            '!=', 'remark', ''
                        ])
                        ->orderBy('remark_id desc')
                        ->asArray()
                        ->one();
                    $patientUserModel->remark = $hissRemark['remark'];
                }

                if (!$patientUserModel->save()) {
                    throw new \Exception(json_encode($patientUserModel->errors), 500);
                }
                // 备注OVER

                /*处理部位数据开始*/
                $patientUsers = User::findOne(['id' => $patientUserModel->id]);
                $hissPositionData = array_unique(array_filter(explode(',', $hissPatient['position'])));
                $bodyPartsIdData = BodyParts::find()->where(['pid' => 0, 'body_parts_name' => $hissPositionData])->select(['id', 'body_parts_name'])->asArray()->all();
                $bodyPartInsertData = [];
                $bodyPartNameData = [];
                foreach ($bodyPartsIdData as $bodyPartsList) {
                    $bodyPartNameData[$bodyPartsList['id']] = $bodyPartsList['body_parts_name'];
                    $flag = \common\models\patient\BodyParts::find()->where(['patient_user_id' => $patientUserModel->id, 'body_parts_id' => $bodyPartsList['id']])->exists();
                    if (!$flag) {
                        $bodyPartInsertData[$bodyPartsList['id']] = [
                            'patient_user_id' => $patientUserModel->id,
                            'body_parts_id' => $bodyPartsList['id'],
                            'created_at' => time(),
                            'updated_at' => time(),
                        ];
                    }
                }
                $bodyPartNameData && $patientUsers->patient_body_parts_name = implode(',', $bodyPartNameData);
                $bodyPartInsertData && Yii::$app->db->createCommand()->batchInsert(\common\models\patient\BodyParts::tableName(), ['patient_user_id', 'body_parts_id', 'created_at', 'updated_at'], $bodyPartInsertData)->execute();
                /*处理部位数据结束*/

                /*标签处理开始*/
                $labelData = array_unique(array_filter(explode(',', $hissPatient['lable'])));
                $tagsData = [];
                $tagsInsertData = [];
                foreach ($labelData as $labelId) {
                    $newTagsId = ConfigService::PATIENT_LABEL[self::$projectId][$labelId] ?? 0;
                    if (!$newTagsId) {
                        continue;
                    }
                    $tagsData[$newTagsId] = $newTagsId;
                    $flag = \common\models\patient\Tags::find()->where(['tags_id' => $newTagsId, 'patient_user_id' => $patientUserModel->id])->exists();
                    // 如果患者不存在这个标签， 则增加
                    if (!$flag) {
                        $tagsInsertData[$newTagsId] = [
                            'patient_user_id' => $patientUserModel->id,
                            'tags_id' => $newTagsId,
                            'created_at' => time(),
                            'updated_at' => time(),
                        ];
                    }
                }
                if ($tagsData) {
                    $tagsNameData = Tags::find()->where(['id' => $tagsData])->select('tags_name')->asArray()->column();
                    $tagsNameData && $patientUsers->patient_tags_name = implode(',', $tagsNameData);
                    $tagsInsertData && Yii::$app->db->createCommand()->batchInsert(\common\models\patient\Tags::tableName(), ['patient_user_id', 'tags_id', 'created_at', 'updated_at'], $tagsInsertData)->execute();
                }
                /*标签处理结束*/


                // 处理患者回访数据
                Model::setTableName('jg_patient_follow');
                $hissFollowData = Model::find()->where(['patient_id' => $hissPatient['patient_id']])->orderBy('follow_id asc')->asArray()->all();
                $followInsertData = [];
                foreach ($hissFollowData as $key => $list) {
                    $flag = Callback::find()->where(['project_id' => self::$projectId, 'patient_user_id' => $patientUserModel->id, 'current_callback_time' => $list['follow_time']])->exists();
                    if ($flag) {
                        continue;
                    }
                    // 回访状态为非白时，病种为非白；为断诊时就诊类型为断诊；为康复发时添加康复发标识
                    if ($key == 0) {
                        if ($list['follow_result'] == 5) {
                            $patientUsers->patient_diseases_id = 3;
                        }
                        if ($list['follow_result'] == 6) {
                            $patientUsers->is_anti_relapse = 1;
                        }
                        if ($list['follow_result'] == 8) {
                            $patientUsers->outpatient_type_id = 1003;
                            $patientUserModel->outpatient_type_id = 1003;
                        }
                    }
                    // OVER

                    $memberInfo = self::getMemberByHissUserId($list['follow_user']);
                    $followInsertData[] = [
                        'project_id' => self::$projectId,
                        'patient_user_id' => $patientUserModel->id,
                        'callback_state_id' => ConfigService::FOLLOW_RESULT[self::$projectId]['id'][$list['follow_result']] ?? 0,
                        'callback_state' => ConfigService::FOLLOW_RESULT[self::$projectId]['title'][$list['follow_result']] ?? '',
                        'callback_way_id' => ConfigService::FOLLOW_TYPE[self::$projectId][$list['follow_type']] ?? 4,
                        'content' => $list['follow'],
                        'current_callback_time' => (int)$list['follow_time'],
                        'outpatient_type_id' => $patientUserModel->outpatient_type_id,
                        'next_callback_time' => $patientUserModel->next_callback_time ?? 0,
                        'next_fuzhen_time' => $hissPatient['order_time'],
                        'member_id' => $memberInfo['id'] ?? 0,
                        'member_name' => $memberInfo['realname'] ?? '',
                        'member_departmement' => $memberInfo['department_name'] ?? '',
                        'created_at' => (int)$list['follow_time'],
                        'updated_at' => (int)$list['follow_time']
                    ];
                }

                $followInsertData && Yii::$app->db->createCommand()->batchInsert(Callback::tableName(),
                    ['project_id', 'patient_user_id', 'callback_state_id', 'callback_state', 'callback_way_id',
                        'content', 'current_callback_time', 'outpatient_type_id', 'next_callback_time',
                        'next_fuzhen_time', 'member_id', 'member_name', 'member_departmement', 'created_at', 'updated_at'
                    ], $followInsertData)->execute();

                // 保存二次编辑的部位、标签、病种、就诊类型、康复发标识
                $patientUsers->save();

                // 处理患者病历数据
                Model::setTableName('jg_patient_detail');
                $hissPatientDetailData = Model::find()->where(['patient_id' => $hissPatient['patient_id']])->asArray()->one();
                if ($hissPatientDetailData) {
                    $model = MedicalRecords::find()->where(['patient_user_id' => $patientUserModel->id, 'project_id' => self::$projectId])->one();
                    if (!$model) {
                        $model = new MedicalRecords;
                    }
                    $model->project_id = self::$projectId;
                    $model->patient_user_id = $patientUserModel->id;
                    $model->sick_time = $hissPatient['first_in_time'];
                    $model->main_desc = $hissPatientDetailData['patient_tell'];
                    $model->now_medical_history = $hissPatientDetailData['case_history_now'];
                    $model->auxiliary_result = $hissPatientDetailData['assist_inspect'];

                    $model->jw_history = '';    // 既往史
                    $model->person_history = '';    // 个人史
                    $model->family_history = $hissPatientDetailData['family_history'];
                    $model->physique_history = $hissPatientDetailData['body_inspect'];
                    $model->diagnose = '';  // 诊断

                    $model->patient_diseases_id = $patientUserModel->patient_diseases_id;
                    $model->diseases_name = (string)PatientDiseases::find()->where(['id' => $patientUserModel->patient_diseases_id])->select('diseases_name')->scalar();
                    if (!$model->save()) {
                        throw new \Exception(json_encode($model->errors), 500);
                    }
                }

                // 处理治疗记录
                // 治疗详情
                Model::setTableName('jg_treat');
                $hissTreat = Model::find()
                    ->alias('a')
                    ->leftJoin('jg_project as b', 'a.project_id = b.project_id')
                    ->leftJoin('jg_treat_detail as c', 'a.detail_id = c.treat_detail_id')
                    ->select([
                        'c.detail_id c_detail_id', 'c.big_position', 'c.small_position', 'c.number', 'c.amount', 'c.add_time c_add_time', 'b.project', 'a.detail_id', 'a.project_id', 'a.real_time_all_buy', 'a.real_time_all_use', 'a.real_time_all_surplus', 'a.treat_add_user', 'a.bak', 'a.add_time'
                    ])
                    ->where([
                        'a.patient_id' => $hissPatient['patient_id']
                    ])
                    ->asArray()
                    ->all();

                $treatData = [];
                $treatDetailData = [];
                foreach ($hissTreat as $value) {
                    Model::setTableName('jg_treat_room');
                    $treatRoom = (int)Model::find()
                        ->select('treat_room_id')
                        ->where([
                            'state' => 1,
                        ])
                        ->andWhere(new Expression("find_in_set('{$value['project_id']}',project_ids)"))
                        ->scalar();
                    $userTreatment = new UserTreatment();
                    $userTreatment->project_id = self::$projectId;
                    $userTreatment->treatment_room_id = ConfigService::TREATROOM[$treatRoom];
                    $userTreatment->patient_card_id = $hissPatient['treat_number'];
                    $userTreatment->clinic_project_id = ConfigService::CLINIC_PROJECT_HK['id'][$value['project_id']];
                    $userTreatment->clinic_project_name = ConfigService::CLINIC_PROJECT_HK['title'][$value['project_id']];
                    $userTreatment->recently_clinic_time = $value['add_time'];
                    $userTreatment->recently_clinic_num = $value['real_time_all_buy'];
                    $userTreatment->total_num = $value['real_time_all_surplus'];
                    $userTreatment->clinic_id = ConfigService::CLINIC[self::$projectId][$hissPatient['consult_room_id']] ?? 0;
                    $userTreatment->clinic_name = ConfigService::CLINIC_ITEM[$hissPatient['consult_room_id']]['name'];
                    $userTreatment->clinic_sort = ConfigService::CLINIC_ITEM[$hissPatient['consult_room_id']]['sort'];
                    $userTreatment->operate_id = ConfigService::HANDLE_LIST['id'][$value['treat_add_user']];
                    $userTreatment->operate_profession = ConfigService::HANDLE_LIST['job'][$value['treat_add_user']];
                    $userTreatment->operate_name = ConfigService::HANDLE_LIST['name'][$value['treat_add_user']];
                    $userTreatment->type = 1;
                    $userTreatment->remark = $value['bak'];
                    $userTreatment->created_at = $value['add_time'];
                    $userTreatment->updated_at = $value['add_time'];

                    $userTreatment->save();
                    /*$treatData[] = [
                        'project_id'=>self::$projectId,
                        'treatment_room_id'=>ConfigService::TREATROOM[$treatRoom],
                        'patient_card_id'=>$hissPatient['treat_number'],
                        'clinic_project_id'=>ConfigService::CLINIC_PROJECT_HK['id'][$value['project_id']],
                        'clinic_project_name'=>ConfigService::CLINIC_PROJECT_HK['title'][$value['project_id']],
                        'recently_clinic_time'=>$value['add_time'],
                        'recently_clinic_num'=>$value['real_time_all_buy'],
                        'total_num'=>$value['real_time_all_surplus'],
                        'clinic_id'=>ConfigService::CLINIC[self::$projectId][$hissPatient['consult_room_id']] ?? 0,
                        'clinic_name'=>ConfigService::CLINIC_ITEM[$hissPatient['consult_room_id']]['name'],
                        'clinic_sort'=>ConfigService::CLINIC_ITEM[$hissPatient['consult_room_id']]['sort'],
                        'operate_id'=>ConfigService::HANDLE_LIST['id'][$value['treat_add_user']],
                        'operate_profession'=>ConfigService::HANDLE_LIST['job'][$value['treat_add_user']],
                        'operate_name'=>ConfigService::HANDLE_LIST['name'][$value['treat_add_user']],
                        'type'=>1,
                        'remark'=>$value['bak'],
                        'created_at'=>$value['add_time'],
                        'updated_at'=>$value['add_time'],
                    ];*/
                    if ($value['c_detail_id']) {
                        $userTreatmentDetail = new UserTreatmentDetail();
                        $userTreatmentDetail->project_id = self::$projectId;
                        $userTreatmentDetail->patient_card_id = $hissPatient['treat_number'];
                        $userTreatmentDetail->clinic_treatment_id = $userTreatment->id;
                        $userTreatmentDetail->body_parts_large_name = $value['big_position'];
                        $userTreatmentDetail->body_parts_small_name = $value['small_position'];
                        $userTreatmentDetail->num = $value['number'];
                        $userTreatmentDetail->dose = $value['amount'];
                        $userTreatmentDetail->created_at = $value['add_time'];
                        $userTreatmentDetail->updated_at = $value['add_time'];

                        $userTreatmentDetail->save();
                    }
                }
                // 治疗记录处理OVER

                $transaction->commit();
            } catch (\Exception $exception) {
                $transaction->rollBack();
                throw new \Exception($exception->getLine() . $exception->getMessage(), 500);
            }
            echo $patientUserModel->id . PHP_EOL;
        }
        file_put_contents($fileName, '*********************项目：' . $projectId . '  END  ***********************' . PHP_EOL . PHP_EOL, FILE_APPEND);
    }

}
